package com.peng.event;

import com.peng.utils.EncryptUtils;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @author : pengyf
 * @version : 1.0
 * @createTime : 2022/1/22 12:17
 * @Description : TODO
 */
public class WakEadBtnsActionListener implements ActionListener {
    private JTextArea pjTextArea;
    private JTextArea rjTextArea;
    private String aesKey = "";//秘钥，必须为16个字符组成
    private String iv = ""; // 偏移量，必须为16个字符组成

    public WakEadBtnsActionListener(JTextArea pjTextArea, JTextArea rjTextArea) {
        this.pjTextArea = pjTextArea;
        this.rjTextArea = rjTextArea;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JButton jButton = (JButton) e.getSource();
        JPanel panel = (JPanel) jButton.getParent();
        String text = pjTextArea.getText();
        if (text == null || "".equals(text)) {
            JOptionPane.showMessageDialog(panel, "请先输入加密参数后在点击！！！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        JTextField myJTextField = (JTextField) panel.getComponent(1);
        aesKey = myJTextField.getText();
        JTextField pylJTextField = (JTextField) panel.getComponent(3);
        iv = pylJTextField.getText();
        if ("".equals(aesKey) || "".equals(iv)) {
            JOptionPane.showMessageDialog(panel, "解析错误，请输入密钥和偏移量！！！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        String reslut = "";
        try {
            switch (jButton.getActionCommand()) {
                case "jiamibtn":
                    reslut = EncryptUtils.aesEncrypt(aesKey, iv, text);
                    break;
                case "jiemibtn":
                    reslut = EncryptUtils.aesDecrypt(aesKey, iv, text);
                    break;
                default:
                    JOptionPane.showMessageDialog(panel, "按钮类型错误", "提示", JOptionPane.WARNING_MESSAGE);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            if (ex.getMessage().indexOf("Given final block not properly padded. Such issues can arise if a bad key is used during decryption") > -1){
                JOptionPane.showMessageDialog(panel, "密钥错误！！！", "提示", JOptionPane.WARNING_MESSAGE);
            }else {
                JOptionPane.showMessageDialog(panel, ex.getMessage(), "提示", JOptionPane.WARNING_MESSAGE);
            }

        }
        rjTextArea.setText(reslut);
    }


}
